from fastapi import FastAPI, HTTPException
from pymongo import MongoClient

app = FastAPI()

# 全局导入 uvicorn
import uvicorn


@app.get("/news")
def get_news(limit: int = 10):
    try:
        client = MongoClient('mongodb://localhost:27017/')
        db = client['news_db']
        collection = db['hot_news']

        results = list(collection.find({}, {'_id': 0}).limit(limit))
        if not results:
            raise HTTPException(status_code=404, detail="未找到新闻数据")
        return results
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


def run_api():
    """启动 API 服务的函数"""
    uvicorn.run(app, host="0.0.0.0", port=8000)